package com.ymh.git.thread.juc;

import java.sql.Connection;
import java.util.Random;

/**
 * Created by aivin on 2018/11/1.
 * 测试数据库连接池
 */
public class AppTest {

    private static DbPoolSemaphore dbPool = new DbPoolSemaphore();

    /**
     * 拿数据库连接的线程
     */
    static class BusThread extends Thread {

        @Override
        public void run() {
            Random random = new Random();//让每个线程持有连接的时间不一样
            long start = System.currentTimeMillis();
            try {
                Connection connection = dbPool.takeConnect();
                System.out.println("Thread_ " + Thread.currentThread().getId() + "_获取数据库连接共耗时【" + (System.currentTimeMillis() - start) + "】毫秒");
                Thread.sleep(100 + random.nextInt(100));//模拟业务操作，线程持有连接查询数据
                System.out.println("查询数据完成，归还连接");
                dbPool.returnConnect(connection);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }


    public static void main(String[] args) {

        for (int i = 0; i < 50; i++) {
            Thread thread = new BusThread();
            thread.start();
        }

    }
}
